from datetime import datetime

import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
from PIL import Image
from tqdm import tqdm
from sklearn.model_selection import cross_val_score

print("加载MNIST数据集")
mnist = datasets.fetch_openml('mnist_784', version=1)
X, y = mnist['data'], mnist['target']

# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

print(f'数据预处理{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train.astype(np.float64))
X_test_scaled = scaler.transform(X_test.astype(np.float64))


print(f'训练模型 {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
clf = SVC(kernel='rbf')
clf.fit(X_train_scaled, y_train)

print(f'模型评估{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
y_pred = clf.predict(X_test_scaled)
print(f"Accuracy: {accuracy_score(y_test, y_pred):.2f}")

# 使用自己的图片进行预测


def predict_image(path):
    # 读取图片并转换为28x28大小
    image = Image.open(path).convert('L').resize((28, 28), Image.ANTIALIAS)
    # 将图片转换为numpy数组，并进行归一化
    img_array = np.array(image) / 255.0
    # 将图片展平为一维数组
    img_flattened = img_array.reshape(1, -1)
    # 标准化
    img_scaled = scaler.transform(img_flattened)
    # 预测
    prediction = clf.predict(img_scaled)
    print(f"Predicted digit: {prediction[0]}")

# 测试自己的图片
predict_image('8.jfif')  # 替换为你的图片路径
